package com.stone.framework.core.context;

import java.util.Map;
import java.util.Optional;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stone.framework.core.model.UserInfo;
import com.stone.framework.core.util.Jwts;

public final class UserContext {

    public static UserInfo getUser() {
        if (!getToken().isPresent()) {
            return UserInfo.EMPTY;
        }
        try { // TODO 实时解析是否存在性能问题
            Map<String, Object> map = Jwts.getPayload(getToken().get());
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return mapper.convertValue(map, UserInfo.class);
        } catch (Exception e) {
            return UserInfo.EMPTY;
        }
    }

    public static String getDefaultUsername() {
        UserInfo user = getUser();
        return UserInfo.EMPTY.equals(user) ? "SYSTEM" : user.getName();
    }

    public static Optional<String> getUsername() {
        UserInfo user = getUser();
        return Optional.ofNullable(user.getName());
    }

    public static String getTerminal() {
        UserInfo user = getUser();
        return user.getTerm();
    }

    private static Optional<String> getToken() {
        return TokenContext.build().get();
    }

}
